#pragma once
#include <iostream>
#include <string>
#include <set>
#include <cstdio>
#include "Log.hpp"
class CommandEx
{
private:
    void LoadConf()
    {
        std::ifstream in(_path_conf);
        if (!in.is_open())
        {
            LOG(FATAL, "open %s error", _path_conf.c_str());
        }
        std::string line;
        while (std::getline(in, line))
        {
            LOG(DEBUG, "load command [%s] success", line.c_str());
            _can_be_excute.insert(line);
        }
        in.close();
    }
    bool IsExist(std::string &cmd)
    {
        size_t pos = cmd.find(' ');

        auto iter = _can_be_excute.find(cmd.substr(0, pos));
        if (iter == _can_be_excute.end())
        {
            return false;
        }
        return true;
    }

public:
    CommandEx(const std::string &path_conf) : _path_conf(path_conf)
    {
        LoadConf();
    }
    std::string Excute(std::string cmd)
    {
        if (IsExist(cmd))
        {
            FILE *fp = popen(cmd.c_str(), "r");
            
            if (fp == NULL)
            {
                return "failed";
            }
            std::string result = cmd;
            result += " excute successfully:\n";
            char buffer[1024];
            while (fgets(buffer, sizeof(buffer), fp) != NULL)
            {
                result += buffer;
            }
            pclose(fp);
            return result;
        }
        else
        {
            return "禁止执行\n";
        }
    }
    ~CommandEx()
    {
    }

private:
    std::set<std::string> _can_be_excute;
    std::string _path_conf;
};